package com.ssm.websocket.entrance;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
// @ServerEndpoint("/chat/{param}")
public class ChatWebSocketHandler extends TextWebSocketHandler {
    final Map<String, WebSocketSession> chat = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        chat.put(session.getId(), session);
        TextMessage message = new TextMessage(session.getId() + "连接");
        for (WebSocketSession s : chat.values()) if (s.isOpen()) s.sendMessage(message);
    }

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        for (WebSocketSession s : chat.values()) if (s.isOpen()) s.sendMessage(message);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.error("chat", exception);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        TextMessage message = new TextMessage(session.getId() + "关闭");
        for (WebSocketSession s : chat.values()) if (s.isOpen()) s.sendMessage(message);
        chat.remove(session.getId());
        session.close();
    }
}